<?php
$loader->requireOnce('includes/EwhImport/EwhImportException.class.php');
/**
 * Processor for ewh import drug/material
 * @package modules.dept_pharmacy.includes.EwhImport
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class EwhImportDrugMaterialProc {
    private $controller;
    private $logger ;
    function __construct($controller) {
        $this->controller = $controller;
        $this->logger = LoggerManager::getLogger('modules.dept_pharmacy.includes.EwhImport.EwhImportDrugMaterialProc');
    }

    /**
     * generate import ticket code
     * [PN][YYYYMMDD + 3 digits]
     * @return [PN][YYYYMMDD + 3 digits]
     */
    public function generateImportTicketCode() {
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        return 	$phaEwhImticket->generateImportTicketCode();
    }


    public function createImportTicket($data) {
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        $result = $phaEwhImticket->createImTicket($data);
        if ($result == null || !isset($result['id']) || $result['id'] == '') {
            //creating fail
            throw new EwhImportException("create imTicket fail",
            EwhErrorCode::IMP_CREAT_IMTICKET_FAIL);
             
        }	else {
            //update seq
            $phaSequences = Celini::newOrdo('PhaSequences');
            $phaSequences->incImTicketSeq();
        }
        return $result;
    }

    public function saveImTicket($imTicketId, $data) {
        $result = array('id'=>'', 'code' => '');
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        
        if (!$phaEwhImticket->isExist($imTicketId)) {
            //TODO dump data and save to log file
            throw new EwhImportException("Save imTicket fail, id ["
            . $imTicketId . "] not exist",
            EwhErrorCode::IMP_SAVE_IMTICKET_FAIL);
        }

        $phaEwhImticket->setup($imTicketId);
        $phaEwhImticket->setData($data);
        $phaEwhImticket->persist();
        $id = $phaEwhImticket->get_id();
        if ($id == null || trim($id) == '') {
            //TODO dump data and save to log file
            throw new EwhImportException("Save imTicket fail",
            EwhErrorCode::IMP_SAVE_IMTICKET_FAIL);
        }
        $result['id'] = $id;
        $result['code'] = $phaEwhImticket->get('imticket_code');
        return $result;
    }

    public function validateInputtedDrugMaterial($phaDrugMaterialId, $proName, $enumItemType) {
        $phaDrugMaterialObj = Celini::newOrdo('DrugMaterial');
        //check drug name valid
        if (!$phaDrugMaterialObj->isExist($phaDrugMaterialId, $proName)) {
            //TODO dump data and save to log file
            throw new EwhImportException("Add drug material fail. drug/material ["
            .
            $proName
            .
            "] not exist",
            EwhErrorCode::IMP_DRUG_MATERIAL_NOT_EXIST);
        }
        //check valid item type         
        if (!$phaDrugMaterialObj->isValidType($phaDrugMaterialId, $enumItemType)) {
            //TODO dump data and save to log file
            throw new EwhImportException("Add drug material fail. drug/material ["
            .
            $proName
            .
            "] wrong type",
            EwhErrorCode::IMP_DRUG_MATERIAL_WRONG_TYPE);
        }
        
       
    }
    
    public function checkDuplicatedDrugMaterial($imTicketId, $phaDrugMaterialId) {
        $phaEwhImticketDetailObj = Celini::newOrdo('PhaEwhImticketDetail');
        //check dupplicated
        if ($phaEwhImticketDetailObj->isExist($imTicketId, $phaDrugMaterialId)) {
            throw new EwhImportException("Add drug material. Duplicate name",
            EwhErrorCode::IMP_DUPLICATE_DRUG_MATERIAL_NAME);
        }      
        
    }

    public function addDrugMaterial($data = array()) {
        //TODO : should check duplicated
        $phaEwhImticketDetailObj = Celini::newOrdo('PhaEwhImticketDetail');
        $imTicketId = $data['pha_ewh_imticket_id'];
        $drugMaterialId = $data['pha_drug_material_id'];


        /*
        //check dupplicated
        //Not check duplicated
        if ($phaEwhImticketDetailObj->isExist($imTicketId, $drugMaterialId)) {
            //TODO dump data and save to log file
            throw new EwhImportException("Add drug material fail",
            EwhErrorCode::IMP_DUPLICATE_DRUG_MATERIAL_NAME);
        }
        */

        $phaEwhImticketDetailObj->setData($data);
        $phaEwhImticketDetailObj->persist();
        $id = $phaEwhImticketDetailObj->get_id();
        if ($id == null || trim($id) == '') {
            //TODO dump data and save to log file
            throw new EwhImportException("Add drug material fail",
            EwhErrorCode::IMP_ADD_DRUG_MATERIAL_FAIL);
        }
        return $id;
    }

    public function deleteDrugMaterial($imTicketId, $imticketDetailId) {
        //TODO : should check this drug belong to creating ticket and
        //this ticket not valuated yet
        $phaEwhImticketDetailObj = Celini::newOrdo('PhaEwhImticketDetail');
        $phaEwhImticketDetailObj->delete($imTicketId, $imticketDetailId);
    }

    public function getImTicketObj($imTicketId) {
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        if (!$phaEwhImticket->isExist($imTicketId)) {
            //TODO dump data and save to log file
            throw new EwhImportException("could not found import ticket id ["
            . $imTicketId . "]",
            EwhErrorCode::IMP_IMTICKET_NOT_FOUND);
        }
        $phaEwhImticket->setup($imTicketId);
        return $phaEwhImticket;
    }
    public function getArrItemsOfImTicket($imTicketId) {
        $phaEwhImticketDetail = Celini::newOrdo('PhaEwhImticketDetail');
        $result = $phaEwhImticketDetail->listAddedDrugMaterial($imTicketId);
        $this->decorateItemsOfImTicket($result);

        return $result;
    }
    public function listAllowSellDMOfGivenNameId($drugMaterialId) {
        $phaEwhImticketDetail = Celini::newOrdo('PhaEwhImticketDetail');
        $result = $phaEwhImticketDetail->listAllowSellDMOfGivenNameId($drugMaterialId);
        $this->decorateAllowSellDM($result);
        return $result;
    }
    
    private function decorateAllowSellDM(&$data = array()){
        $arrUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        foreach ($data as &$item) {
            $item['im_expired_date_formatted'] = L10nHelper::renderDateTime($item['im_expired_date']);
            $item['im_expired_date_to_number'] = str_replace(':','', str_replace(" ", '',str_replace("-", '',$item['im_expired_date'])));
            $item['remain_quantity_formatted'] = L10nHelper::renderNumber($item['remain_quantity']);
            if (isset($arrUnit[$item['enum_unit_import_sell']])) {
                $item['enum_unit_import_sell_text'] = $arrUnit[$item['enum_unit_import_sell']];

            } else {
                $item['enum_unit_import_sell_text'] = '';
            }
        }

    }
    private function decorateItemsOfImTicket(&$data = array()){
        $arrUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        foreach ($data as &$item) {
            $item['im_expired_date_formatted'] = L10nHelper::renderDateTime($item['im_expired_date']);
            $item['im_unit_price_formatted'] = L10nHelper::renderNumber($item['im_unit_price']);
            $item['total_price_formatted'] = L10nHelper::renderNumber($item['total_price']);
            if (isset($arrUnit[$item['enum_unit_import_sell']])) {
                $item['enum_unit_import_sell_text'] = $arrUnit[$item['enum_unit_import_sell']];

            } else {
                $item['enum_unit_import_sell_text'] = '';
            }
        }

    }
    public function searchImticket($filter = array()) {
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        $result = $phaEwhImticket->searchImticket($filter);
        $this->decorateSearchImTicketResult($result);       
        return $result;        
    }
    public function deleteImticket($imTicketId) {
        $phaEwhImticket = Celini::newOrdo('PhaEwhImticket');
        $result = $phaEwhImticket->deleteImticket($imTicketId);               
        return $result;        
    }
    
    private function decorateSearchImTicketResult(&$data = array()) {
        $arrItemType = Utils::getEnumArrayKey(EnumerationConstant::PHA_ITEM_TYPE);
        foreach ($data as &$item) {
            $item['date_formatted'] = L10nHelper::renderDateTime($item['date']);            
            if (isset($arrItemType[$item['enum_item_type']])) {
                $item['enum_item_type_text'] = $arrItemType[$item['enum_item_type']];

            } else {
                $item['enum_item_type_text'] = '';
            }
        }
        
    }


}
?>